package com.star.platforms;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.star.platforms.netty.NettyHelper;
import com.star.platforms.pojo.IceDataBean;
import com.star.platforms.redis.RedisUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.Timer;
import java.util.zip.GZIPInputStream;

@Log4j2
@Component
@EnableScheduling
public class Test implements ApplicationRunner {
    WebSocketClient webSocketClient;
    @Resource
    private RedisUtils redisUtil;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        //比特币初始化
        initBitCoinSocket();
        //雪球网数据初始化
       // initStockData();


           /*  System.setProperty("proxyType", "4"); // 设置代理类型，4应该是指http
        System.setProperty("proxyPort", "7890"); // 设置代理的端口号
        System.setProperty("proxyHost", "192.168.3.232"); // 设置代理的ip地址
        System.setProperty("proxySet", "true"); // 使代理生效*/
       /* File file = new File("D:\\server_client.json");
        FileInputStream serviceAccount =
                new FileInputStream(file);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .build();

        FirebaseApp.initializeApp(options);*/
        // Initialize the default app
     /*   FirebaseApp defaultApp = FirebaseApp.initializeApp("Bamboo Credit");

        System.out.println(defaultApp.getName());*/
        // This registration token comes from the client FCM SDKs.

    }

    /**
     * 雪球网数据
     */
    private void initStockData() {
        iceStockTimer();

    }

    @Scheduled(fixedRate =5* 1000)
    private void iceStockTimer() {
        Calendar cal= Calendar.getInstance();
/*        if (cal.get(Calendar.HOUR_OF_DAY)<=9||cal.get(Calendar.HOUR_OF_DAY)>=15){
            System.out.println("过时间了（9:00-15:00)");
            return;
        }*/
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://stock.xueqiu.com/v5/stock/realtime/quotec.json?symbol=SH000001");
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                IceDataBean iceDataBean = new Gson().fromJson(content, IceDataBean.class);
                redisUtil.set("iceData", iceDataBean);
                System.out.println(content);
                if (iceDataBean.getError_code() == 0){
                    new NettyHelper().pushToAll(new Gson().toJson(iceDataBean.getData()));
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 比特币初始化
     */
    private void initBitCoinSocket() throws URISyntaxException, InterruptedException {
        getWebSocketClient();
      //  bitCoinHeartTimer();
        Thread.sleep(10000);
        String data = JSONObject.toJSONString(new Data("market.btcusdt.kline.1min", "id1"));
        System.out.println(data);
        if (webSocketClient != null) {
            webSocketClient.send(data);
        }
    }

    private WebSocketClient getWebSocketClient() throws URISyntaxException {
        WebSocketClient webSocketClient = new WebSocketClient(new URI("wss://api-aws.huobi.pro/ws")) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                System.out.println("[websocket] 连接成功");
            }

            @Override
            public void onMessage(String s) {

            }

            @Override
            public void onMessage(ByteBuffer bytes) {
                try {
                    String message = new String(ZipUtil.解压GZIP数据(bytes.array()), "UTF-8");/* 解开GZIP压缩 */
                    JSONObject jsonObject = JSONObject.parseObject(message);/* 转换成Json */
                    System.out.println("收到的消息：" + message); //收到Ping消息
                    if (null != jsonObject.getString("ping")) {/* 判断是不是Ping */
                          System.out.println("收到的消息：" + message); //收到Ping消息
                        JSONObject json = new JSONObject();
                        json.put("pong", System.currentTimeMillis());
                        /* System.out.println("发送消息：" + json.toString());*/
                        send(json.toString());/* 发送Pong回应 */
                    } else {
                        if (null!=jsonObject.getString("ping")){
                            return;
                        }
                        /*    System.err.println("收到的消息：" + message);*/
                        new NettyHelper().pushToAll(message);
                        // JSONObject tick = jsonObject.getJSONObject("tick");
                      /*  Double p = tick.getDouble("close");
                        System.out.println("===》 "+p+" 《===");*/
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                System.out.println("[websocket] 连接关闭");

            }

            @Override
            public void onError(Exception e) {
                System.out.println("[websocket] 连接错误");

            }
        };
        webSocketClient.addHeader("origin","https://exchange.blockchain.com");
        webSocketClient.connect();

        return webSocketClient;

    }


  /*  *//**
     * 比特币定时任务
     *//*
    @Scheduled(fixedRate = 5000)
    public synchronized void bitCoinHeartTimer() throws URISyntaxException {
        // webSocketClient.send();
        if (webSocketClient == null || webSocketClient.isClosed()) {
            webSocketClient = getWebSocketClient();
        } else {
            webSocketClient.send("{\"ping\": 18212553000}");
        }
    }*/

    class Data implements Serializable {
        String sub = "market.btcusdt.kline.1min";
        String id = "id1";

        public String getSub() {
            return sub;
        }

        public void setSub(String sub) {
            this.sub = sub;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public Data(String sub, String id) {
            this.sub = sub;
            this.id = id;
        }

    }


}

/* Zip工具类 */
class ZipUtil {
    public static byte[] 解压GZIP数据(byte[] depressData) throws Exception {
        ByteArrayInputStream is = new ByteArrayInputStream(depressData);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        GZIPInputStream gis = new GZIPInputStream(is);
        int count;
        byte data[] = new byte[1024];
        while ((count = gis.read(data, 0, 1024)) != -1) {
            os.write(data, 0, count);
        }
        gis.close();
        depressData = os.toByteArray();
        os.flush();
        os.close();
        is.close();
        return depressData;
    }
}